package com.zeroone.star.publish.controller;


import com.zeroone.star.project.vo.JsonVO;
import com.zeroone.star.publish.entity.ModifyUserDTO;
import com.zeroone.star.publish.entity.TokenUserDTO;
import com.zeroone.star.publish.entity.User;
import com.zeroone.star.publish.mapper.UserMapper;
import com.zeroone.star.publish.service.impl.UserServiceImpl;
import com.zeroone.star.publish.utils.JwtUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sql.rowset.serial.SerialBlob;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author car
 * @since 2024-03-02
 */
@RestController
@RequestMapping("/publish/user")
public class UserController {


    @Resource
    private UserServiceImpl userService;

    @PostMapping("/addUser")//该方法应响应发送到"/addUser"路径的HTTP POST请求。
    @ApiOperation("注册")// 这是一个Swagger注解，用于给API操作添加描述。此处标明该方法实现的是“注册”功能(在api接口页显示）。

    //@RequestBod注解：方法参数user用请求体中的JSON数据自动反序列化填充。（接受用户输入的数据）
    // User是已经封装好的类，有注册的用户信息（如用户名、密码、邮箱等）。
    public JsonVO addUser(@RequestBody User user) {
        Integer i = userService.insertUser(user);//用userService接口的insertUser方法，传入接收到的user对象
        //方法返回一个整数i 用来判断注册成功与否
        if (i == 1)
            return JsonVO.success("注册成功");
        else
            return JsonVO.fail("注册失败");
    }


    @PostMapping("/deleteUser")
    @ApiOperation("删除用户")
    public JsonVO deleteUser(Long id) {
        Integer i = userService.deleteUser(id);
        if (i == 1)
            return JsonVO.success("删除成功");
        else
            return JsonVO.fail("删除失败");
    }


    @PostMapping("/modifyUserPermission")
    @ApiOperation("修改用户权限")
    public JsonVO modifyUserPermission(Integer id) {
        return null;
    }

    @PostMapping("/modifyUserPassword")
    @ApiOperation("修改用户密码")
    public JsonVO modifyUserPassword(Long id, String password, String newPassword) {
        User user = userService.modifyUserPassword(id, password, newPassword);
        if (user != null)
            return JsonVO.success("修改成功");
        return JsonVO.fail("修改失败,请检查原密码是否正确");
    }


    @PostMapping("/login")
    @ApiOperation("登录")
    public JsonVO login(@RequestParam String uid, @RequestParam String password) {
        Long id = Long.valueOf(uid);
        if (userService.login(id, password)) {
            return JsonVO.success("登录成功");
        }
        return JsonVO.fail("登录失败，请检查你的账号密码是否正确");
    }
    @GetMapping("/decodeCurrentUser")
    @ApiOperation("解析当前用户token信息")
    public  JsonVO<TokenUserDTO> decodeCurrentUser(@RequestParam String token){
        JwtUtils jwtUtils = new JwtUtils();
        TokenUserDTO decode = jwtUtils.decode(token);
        JsonVO<TokenUserDTO> tokenUserDTOJsonVO = new JsonVO<>();
        tokenUserDTOJsonVO.setData(decode);
        return tokenUserDTOJsonVO;
    }


    @GetMapping("/getCurrentMessage")
    @ApiOperation("获取当前用户信息")
    public  JsonVO<User> getCurrentMessage(@RequestParam String id){
        JsonVO<User> userJsonVO = new JsonVO<>();
        User user = userService.selectUserById(Long.valueOf(id));
        userJsonVO.setData(user);
        return userJsonVO;
    }

    /**
     * 上传或更新用户头像
     */
    @PostMapping("/uploadAvatar")
    @ApiOperation("上传/更新用户头像")
    public JsonVO uploadAvatar(@RequestParam Integer userId, @RequestParam MultipartFile avatarFile) throws IOException {
        byte[] avatarBytes = avatarFile.getBytes();

        Blob avatarBlob = null;
        try {
            avatarBlob = new SerialBlob(avatarBytes);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        Integer result = userService.updateAvatar(userId, avatarBlob);

        if (result == 1) {
            return JsonVO.success("头像上传成功");
        } else {
            return JsonVO.fail("头像上传失败");
        }
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/modifyUser")
    @ApiOperation("修改用户信息")
    public JsonVO modifyUser(@RequestBody ModifyUserDTO modifiedUser) {
        boolean success = userService.modifyUser(modifiedUser);

        if (success) {
            return JsonVO.success("用户信息修改成功");
        } else {
            return JsonVO.fail("用户信息修改失败");
        }
    }


}

